package com.nuaa.controller.examples;

import java.io.File;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.nuaa.utils.AjaxMsg;

@Controller
@RequestMapping("upload")
public class UploadController {
	
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public String to(){
		return "examples/upload";
	}
	
	@ResponseBody
	@RequestMapping(value="/submit.do",method = RequestMethod.POST)
	public AjaxMsg upload(MultipartFile file,HttpServletRequest request){
		AjaxMsg msg = new AjaxMsg();
		try {
			byte[] fileByte = file.getBytes();
			String dir = System.getProperty("webApp.path")+"file";
			System.out.println(dir);
			String fileName = file.getOriginalFilename();
			String[] names = fileName.split("\\.");
			String lastNode = names[names.length-1];
//			System.out.println(file.getName()+"::::"+file.getOriginalFilename());
			
			String newFileName = UUID.randomUUID()+"."+lastNode;
			
			String allPath = dir+"/"+newFileName;
			File upFile = new File(allPath);
			FileCopyUtils.copy(fileByte, upFile);
			msg.setResult(newFileName);
			msg.setMsg("上传成功！");
			msg.setSuccess(true);
			return msg;
			
		} catch (Exception e) {
			msg.setMsg("上传失败");
			msg.setSuccess(false);
			e.printStackTrace();
			return msg;
		}
	}
}
